<template>
    <div v-loading="loading">

        <el-header style="padding-left: 0">
            <el-button type="primary"  @click.stop="addPic">选择图片</el-button>
            <input type="file" accept="image/*" ref="f1" @click="onSelectFile" @change="onFileChange" style="display: none;" multiple>
        </el-header>

        <el-form class="mb2" :model="$data" ref="imageForm" >

            <el-table :data="imgUrls" :border="true">
                <el-table-column label="图片">
                    <template slot-scope="scope">
                        <el-image style="width:10rem;height: 10rem" fit="cover" :src="scope.row.b64"   :preview-src-list="previewImages"></el-image>
                    </template>
                </el-table-column >
                <el-table-column >
                    <template slot-scope="scope">

                        <el-row>
                            <el-col :span="12">

                                <span v-if="scope.row.status === 0">未上传</span>
                                <span v-else-if="scope.row.status === 1" style="color: #67C23A">已上传</span>
                                <span v-else-if="scope.row.status === 2" style="color:#F56C6C">上传失败</span>
                            </el-col>
                            <el-col :span="12">
                                <el-button size="mini" type="danger" @click="unselect(scope.$index,scope.row)">删除</el-button>

                            </el-col>

                        </el-row>
                        <el-row>
                            <el-select v-model="scope.row.type" :prop="'imgUrls.'+scope.$index+'.type'" :rules="{required:true,message:'请选择图片的类型',trigger:'blur'}">
                                <el-option v-for="v in filetype" :key="v.value" :label="v.value" :value="v.value"></el-option>
                            </el-select>

                        </el-row>

                    </template>
                </el-table-column>


            </el-table>

        </el-form>

        <el-footer style="padding-left: 0">
            <el-row :gutter="5">
                <el-col :span="12">
                    <el-button class="w100per" type="primary" @click="postAllFile">全部上传</el-button>

                </el-col>
                <el-col :span="12">
                    <el-button class="w100per" type="primary" @click="next">下一步</el-button>
                </el-col>
            </el-row>

        </el-footer>

    </div>

</template>

<script>

    import {mapActions,mapState} from 'vuex'
    import copy from "fast-copy";

    export default {
        name: 'Upload',
        data: function () {
            return {
                imgUrls: [],

                isPhoto: true,

                isModify: false,
                previewImg: '',
                isPreview: false,
                slide: [],
                loading: false,
                filetype:[]
            }
        },




        created() {
            this.$api.getFileType()
                .then(res=>{
                    let t = [];
                    res.data.forEach(v=>{
                        t.push({ value:v.type})
                    })
                    this.filetype = t;
                })
            // if(this.AH !== ""){
            //     this.getImageList()
            // }


        },

        watch: {
            trialExtraId(nv){
                if (nv !== 0) {
                    this.getImageList()
                }
            },

            imgUrls: 'toggleAddPic',


        },

        computed: {
            previewImages() {
                let ret = [];
                this.imgUrls.forEach((v, i) => {
                    ret.push(v.b64);
                });
                return ret;
            },

            ...mapState([
                'step','submitData','AH','trialExtraId'
            ])
        },

        methods: {

            ...mapActions([
               'setStep','setSubmitData',
            ]),

            getImageList(){

                this.$api.getImageList({AH:this.AH ,trial_extra_id:this.trialExtraId})
                    .then(res=>{
                        let imgUrls = [];
                        res.data.map((v)=>{
                            imgUrls.push({status : 1,type:v.type,b64:v.file_url,id:v.id})
                        });
                        this.imgUrls = imgUrls;
                    })
            },

            closePage(){

                let ret = window.confirm('确定关闭页面？')
                if (ret) {
                    window.history.back(-1);
                }
            },

            onSelectFile() {

                this.$refs.f1.value = '';
            },

            /**
             * 取消选择
             * **/
            unselect(index, item) {

                if(item.id && item.id !== ""){

                    this.$api.deleteImage({id:item.id,AH:this.AH,trial_extra_id: this.trialExtraId})
                        .then(res=>{
                            this.imgUrls.splice(index, 1);
                        })
                }else{
                    this.imgUrls.splice(index, 1);
                }
            },

            /**
             * 一键上传
             */
            async postAllFile() {

                if (this.imgUrls.length === 0) {
                    this.$message({
                        type: 'warning',
                        message: '请选择文件'
                    })
                } else {
                    this.loading = true;
                    let imgUrlsNew = [];
                    let promiseArr = [];

                    let p = null;

                    for (let i = 0;i< this.imgUrls.length;i++) {
                        p = this.imgUrls[i];
                        if (p.status === 0 || p.status === 2) {
                            if(p.type === ""){
                                alert('请选择文件类型再上传')
                                this.loading = false
                                return false;
                            }
                        }
                    }

                    for (let i = 0;i< this.imgUrls.length;i++) {
                        p = this.imgUrls[i];
                        if (p.status === 0 || p.status === 2) {
                            promiseArr.push( this.postFile(p.file))
                        } else {
                            promiseArr.push(Promise.resolve(p.status))
                        }
                    }

                    try{
                        let [successCount , failCount] = [0,0];
                        let values = await Promise.all(promiseArr.map(p=> p.catch(e=>e)))
                        values.map((res,i) =>{

                            let img = copy(this.imgUrls[i]);

                            if(typeof(res) !== 'number' ){

                                if ( res.code === 1) {
                                    img.status = 1;//上传成功
                                    img.id = res.data.id;
                                    successCount++;
                                } else {
                                    img.status = 2;//上传失败
                                    failCount++;
                                }

                            }

                            imgUrlsNew.push(img)
                        });

                        this.imgUrls = imgUrlsNew;

                        if (successCount === 0 && failCount === 0) {
                            this.$message({
                                type: 'warning',
                                message: `无待上传的文件`
                            });
                        }else{
                            this.$message({
                                type: failCount>0?'warning':"success",
                                message: `上传完成，成功：${successCount}个，失败：${failCount}个`
                            });
                        }
                    }catch (e) {
                        console.log(e)
                    }
                    this.loading = false;


                }
            },

            /**
             * 单个上传
             * @param file
             * @returns {Promise<AxiosResponse<any>>}
             */
            postFile(file) {
                let forms = new FormData();
                let configs = {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                forms.append('AH',this.AH)
                forms.append('file', file)
                forms.append('trial_extra_id',this.trialExtraId)
                return this.$api.upload( forms, configs)

            },
            toggleAddPic: function () {
                let vm = this;
                vm.isPhoto = vm.imgUrls.length < 1;
            },
            addPic: function (e) {

                this.$refs.f1.click();
                return false;
            },

            onFileChange: function (e) {

                var files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;

                this.createImage(files, e);


            },

            createImage: function (file, e) {
                for(let i = 0;i< file.length;i++){

                    let reader = new FileReader();
                    reader.readAsDataURL(file[i])
                    reader.onload = (e) => {
                        this.imgUrls.push({b64: e.target.result, file: file[i], status: 0,type:"",id:0})
                    }
                }
            },


            next() {


                this.$refs['imageForm'].validate()
                    .then(res=>{

                        let trialFile = [];
                        this.imgUrls.map(v=>{
                            if(v.status === 1){
                                trialFile.push({id:v.id,url:v.b64,type:v.type})
                            }
                        });
                        let sd = copy(this.submitData);
                        sd.trialFile = trialFile;
                        this.setSubmitData(sd)
                        this.setStep(this.step+1)
                    })

            }
        }
    }
</script>

<style scoped>

</style>
